taler-rust

GNU Taler code in Rust. Largely core banking integrations.
Log | Files | Refs | Submodules | README | LICENSE

lib.rs (18726B)


      1 /*
      2   This file is part of TALER
      3   Copyright (C) 2026 Taler Systems SA
      4 
      5   TALER is free software; you can redistribute it and/or modify it under the
      6   terms of the GNU Affero General Public License as published by the Free Software
      7   Foundation; either version 3, or (at your option) any later version.
      8 
      9   TALER is distributed in the hope that it will be useful, but WITHOUT ANY
     10   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
     11   A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
     12 
     13   You should have received a copy of the GNU Affero General Public License along with
     14   TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
     15 */
     16 
     17 use proc_macro::TokenStream;
     18 use quote::quote;
     19 use syn::{
     20     Data, DeriveInput, Error, Expr, Field, Fields, ItemStruct, Lit, LitStr, Meta, parse::Parser,
     21     parse_macro_input,
     22 };
     23 
     24 #[proc_macro_derive(EnumMeta, attributes(enum_meta, code))]
     25 pub fn derive_domain_code(input: TokenStream) -> TokenStream {
     26     let input = parse_macro_input!(input as DeriveInput);
     27     let name = &input.ident;
     28 
     29     // Parse features
     30     let mut enabled_doc = false;
     31     let mut enabled_domain_code = false;
     32     let mut enabled_str = false;
     33 
     34     for attr in &input.attrs {
     35         if attr.path().is_ident("enum_meta")
     36             && let Err(e) = attr.parse_nested_meta(|meta| {
     37                 if meta.path.is_ident("Description") {
     38                     enabled_doc = true;
     39                 } else if meta.path.is_ident("DomainCode") {
     40                     enabled_domain_code = true;
     41                 } else if meta.path.is_ident("Str") {
     42                     enabled_str = true;
     43                 } else {
     44                     return Err(meta.error("unknown enum_meta option"));
     45                 }
     46                 Ok(())
     47             })
     48         {
     49             return e.to_compile_error().into();
     50         }
     51     }
     52 
     53     let repr_type = input.attrs.iter().find_map(|attr| {
     54         if !attr.path().is_ident("repr") {
     55             return None;
     56         }
     57         let mut found = None;
     58         attr.parse_nested_meta(|it| {
     59             found = it.path.get_ident().cloned();
     60             Ok(())
     61         })
     62         .unwrap();
     63         found
     64     });
     65 
     66     let variants = if let Data::Enum(data) = &input.data {
     67         &data.variants
     68     } else {
     69         return Error::new(input.ident.span(), "EnumMeta only supports enums")
     70             .to_compile_error()
     71             .into();
     72     };
     73 
     74     // Helper: extract the first string literal from a name-value attribute.
     75     let extract_str_attr = |variant: &syn::Variant, ident: &str| -> Option<String> {
     76         variant.attrs.iter().find_map(|a| {
     77             if a.path().is_ident(ident)
     78                 && let Meta::NameValue(nv) = &a.meta
     79                 && let Expr::Lit(expr) = &nv.value
     80                 && let Lit::Str(s) = &expr.lit
     81             {
     82                 Some(s.value())
     83             } else {
     84                 None
     85             }
     86         })
     87     };
     88 
     89     let mut entries = Vec::new();
     90     let mut description_arms = Vec::new();
     91     let mut code_arms = Vec::new();
     92     let mut from_str_arms = Vec::new();
     93     let mut as_ref_arms = Vec::new();
     94     let mut try_from_arms = Vec::new();
     95 
     96     for variant in variants {
     97         let v_ident = &variant.ident;
     98         let v_str = variant
     99             .attrs
    100             .iter()
    101             .find_map(|attr| {
    102                 if attr.path().is_ident("enum_meta") {
    103                     let mut res = None;
    104                     let _ = attr.parse_nested_meta(|meta| {
    105                         if meta.path.is_ident("rename") {
    106                             let value: LitStr = meta.value()?.parse()?;
    107                             res = Some(value.value());
    108                         }
    109                         Ok(())
    110                     });
    111                     res
    112                 } else {
    113                     None
    114                 }
    115             })
    116             .unwrap_or_else(|| v_ident.to_string());
    117 
    118         if repr_type.is_some() {
    119             if let Some((_, discriminant)) = &variant.discriminant {
    120                 try_from_arms.push(quote! { #discriminant => Ok(Self::#v_ident) });
    121             } else {
    122                 return Error::new(v_ident.span(), "missing discriminant expression")
    123                     .to_compile_error()
    124                     .into();
    125             };
    126         }
    127 
    128         // Single pass: collect doc and code in one go, then use what's needed.
    129         let doc =
    130             enabled_doc.then(|| extract_str_attr(variant, "doc").map(|s| s.trim().to_string()));
    131         let code = (enabled_domain_code).then(|| extract_str_attr(variant, "code"));
    132 
    133         if let Some(doc) = doc {
    134             let doc = match doc {
    135                 Some(d) => d,
    136                 None => {
    137                     return Error::new(
    138                         v_ident.span(),
    139                         format!("variant `{v_str}` is missing `/// documentation`"),
    140                     )
    141                     .to_compile_error()
    142                     .into();
    143                 }
    144             };
    145             description_arms.push(quote! { Self::#v_ident => #doc });
    146         }
    147 
    148         if let Some(code) = code {
    149             let code = match code {
    150                 Some(c) => c,
    151                 None => {
    152                     return Error::new(
    153                         v_ident.span(),
    154                         format!("variant `{v_str}` is missing `#[code = \"...\"]`"),
    155                     )
    156                     .to_compile_error()
    157                     .into();
    158                 }
    159             };
    160             from_str_arms.push(quote! { #code => Ok(Self::#v_ident) });
    161             code_arms.push(quote! { Self::#v_ident => #code });
    162         } else if enabled_str {
    163             from_str_arms.push(quote! { #v_str => Ok(Self::#v_ident) });
    164         }
    165 
    166         if enabled_str {
    167             as_ref_arms.push(quote! { Self::#v_ident => #v_str });
    168         }
    169         entries.push(quote! { Self::#v_ident, });
    170     }
    171 
    172     let mut expanded = quote! {
    173         impl #name {
    174             /// Returns a slice of all enum variants.
    175             pub const entries: &'static [Self] = &[#(#entries)*];
    176         }
    177     };
    178 
    179     if enabled_doc {
    180         expanded.extend(quote! {
    181             impl #name {
    182                 /// Returns the documentation description associated
    183                 pub fn description(&self) -> &'static str {
    184                     match self { #(#description_arms),* }
    185                 }
    186             }
    187         });
    188     }
    189 
    190     if enabled_domain_code {
    191         expanded.extend(quote! {
    192             impl #name {
    193                 /// Returns the domain code associated
    194                 pub fn code(&self) -> &'static str {
    195                     match self { #(#code_arms),* }
    196                 }
    197             }
    198         });
    199     }
    200 
    201     if enabled_str {
    202         expanded.extend(quote! {
    203             impl #name {
    204                 pub fn as_str(&self) -> &'static str {
    205                     match self { #(#as_ref_arms),* }
    206                 }
    207             }
    208 
    209             impl AsRef<str> for #name {
    210                 fn as_ref(&self) -> &str {
    211                     self.as_str()
    212                 }
    213             }
    214 
    215             impl std::fmt::Display for #name {
    216                 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    217                     f.write_str(self.as_ref())
    218                 }
    219             }
    220         });
    221     }
    222 
    223     if enabled_domain_code || enabled_str {
    224         let unknown_label = if enabled_domain_code { "code" } else { "name" };
    225         expanded.extend(quote! {
    226             impl std::str::FromStr for #name {
    227                 type Err = String;
    228                 fn from_str(s: &str) -> Result<Self, Self::Err> {
    229                     match s {
    230                         #(#from_str_arms,)*
    231                         _ => Err(format!("Unknown {0} for {1}: {2}", #unknown_label, stringify!(#name), s))
    232                     }
    233                 }
    234             }
    235         });
    236     }
    237 
    238     if let Some(repr) = repr_type {
    239         expanded.extend(quote! {
    240             impl TryFrom<#repr> for #name {
    241                 type Error = #repr;
    242                 fn try_from(value: #repr) -> Result<Self, Self::Error> {
    243                     match value {
    244                         #(#try_from_arms,)*
    245                         _ => Err(value),
    246                     }
    247                 }
    248             }
    249         });
    250     }
    251 
    252     TokenStream::from(expanded)
    253 }
    254 
    255 #[proc_macro_attribute]
    256 pub fn api_config(attr: TokenStream, item: TokenStream) -> TokenStream {
    257     // 1. Cleanly parse the string attribute argument
    258     let api_name_lit = parse_macro_input!(attr as LitStr);
    259     let api_name_value = api_name_lit.value();
    260 
    261     // 2. Parse the target struct
    262     let mut input_struct = parse_macro_input!(item as ItemStruct);
    263     let struct_name = &input_struct.ident;
    264 
    265     // 3. Generate deterministic function names for serialization AND deserialization
    266     let struct_lower = struct_name.to_string().to_lowercase();
    267     let serialize_fn_ident = syn::Ident::new(
    268         &format!("_serialize_api_name_for_{}", struct_lower),
    269         proc_macro2::Span::call_site(),
    270     );
    271     let deserialize_fn_ident = syn::Ident::new(
    272         &format!("_deserialize_api_name_for_{}", struct_lower),
    273         proc_macro2::Span::call_site(),
    274     );
    275 
    276     // 4. Convert identifiers to string paths for Serde attributes
    277     let serialize_fn_str = serialize_fn_ident.to_string();
    278     let deserialize_fn_str = deserialize_fn_ident.to_string();
    279 
    280     let crate_path = if std::env::var("CARGO_CRATE_NAME").unwrap_or_default() == "taler_common" {
    281         quote! { crate }
    282     } else {
    283         quote! { ::taler_common }
    284     };
    285 
    286     // 5. Inject the `name` field with BOTH serialization and deserialization hooks
    287     if let Fields::Named(ref mut fields) = input_struct.fields {
    288         fields.named.insert(
    289             0,
    290             Field::parse_named
    291                 .parse2(quote! {
    292                     #[serde(
    293                         serialize_with = #serialize_fn_str,
    294                         deserialize_with = #deserialize_fn_str
    295                     )]
    296                     pub name: ()
    297                 })
    298                 .unwrap(),
    299         );
    300         fields.named.insert(
    301             1,
    302             Field::parse_named
    303                 .parse2(quote! {
    304                     pub version: #crate_path::api::LibtoolVersion
    305                 })
    306                 .unwrap(),
    307         );
    308         fields.named.insert(
    309             2,
    310             Field::parse_named
    311                 .parse2(quote! {
    312                     pub implementation: Option<&'a str>
    313                 })
    314                 .unwrap(),
    315         );
    316     } else {
    317         return syn::Error::new_spanned(
    318             input_struct,
    319             "#[api_config] only works on structs with named fields",
    320         )
    321         .to_compile_error()
    322         .into();
    323     }
    324 
    325     let expanded = quote! {
    326         #input_struct
    327 
    328         #[doc(hidden)]
    329         #[allow(non_snake_case)]
    330         pub fn #serialize_fn_ident<S>(_: &(), s: S) -> ::std::result::Result<S::Ok, S::Error>
    331         where
    332             S: ::serde::Serializer
    333         {
    334             s.serialize_str(#api_name_value)
    335         }
    336 
    337         #[doc(hidden)]
    338         #[allow(non_snake_case)]
    339         pub fn #deserialize_fn_ident<'de, D>(deserializer: D) -> ::std::result::Result<(), D::Error>
    340         where
    341             D: ::serde::Deserializer<'de>,
    342         {
    343             let s: ::std::string::String = ::serde::Deserialize::deserialize(deserializer)?;
    344             if s == #api_name_value {
    345                 Ok(())
    346             } else {
    347                 Err(::serde::de::Error::custom(::std::format!(
    348                     "invalid API name: expected '{}', found '{}'",
    349                     #api_name_value, s
    350                 )))
    351             }
    352         }
    353     };
    354 
    355     TokenStream::from(expanded)
    356 }
    357 
    358 /// Run an async database test with a pool initialized from `crate::CONFIG_SOURCE`.
    359 ///
    360 /// An explicit config expression can override the default. Components without
    361 /// installed configuration can use `#[db_test(sql_dir = "db", component = "name")]`.
    362 /// Use `#[db_test(raw)]` to reserve a database without initializing schemas; its
    363 /// argument is `PgConnectOptions` instead of `PgPool`.
    364 /// Initialized tests can take a `PgPool`, a `PoolConnection<Postgres>`, a
    365 /// `PgConnection`, or `&mut PgConnection`. A pool and a connection may be combined
    366 /// in either order. The function must return `()` or `Result<(), E>`.
    367 /// Do not combine this attribute with `#[test]` or `#[tokio::test]`.
    368 #[proc_macro_attribute]
    369 pub fn db_test(attr: TokenStream, item: TokenStream) -> TokenStream {
    370     let input = parse_macro_input!(item as syn::ItemFn);
    371     match expand_db_test(attr.into(), input) {
    372         Ok(tokens) => tokens.into(),
    373         Err(error) => error.to_compile_error().into(),
    374     }
    375 }
    376 
    377 fn expand_db_test(
    378     attr: proc_macro2::TokenStream,
    379     input: syn::ItemFn,
    380 ) -> syn::Result<proc_macro2::TokenStream> {
    381     let sig = &input.sig;
    382     if sig.asyncness.is_none()
    383         || !(1..=2).contains(&sig.inputs.len())
    384         || !sig.generics.params.is_empty()
    385         || sig.generics.where_clause.is_some()
    386         || sig.constness.is_some()
    387         || !matches!(sig.safety, syn::Safety::Default)
    388         || sig.abi.is_some()
    389         || sig.variadic.is_some()
    390         || sig
    391             .inputs
    392             .iter()
    393             .any(|arg| matches!(arg, syn::FnArg::Receiver(_)))
    394     {
    395         return Err(Error::new_spanned(
    396             sig,
    397             "db_test requires an async function with one or two database arguments and no generics",
    398         ));
    399     }
    400     for attr in &input.attrs {
    401         if attr
    402             .path()
    403             .segments
    404             .last()
    405             .is_some_and(|s| s.ident == "test")
    406         {
    407             return Err(Error::new_spanned(
    408                 attr,
    409                 "db_test supplies the test attribute; remove the other test attribute",
    410             ));
    411         }
    412     }
    413 
    414     let name = &sig.ident;
    415     let callback = || -> syn::Result<proc_macro2::TokenStream> {
    416         let mut has_pool = false;
    417         let mut has_conn = false;
    418         let mut args = Vec::new();
    419         for arg in &sig.inputs {
    420             let syn::FnArg::Typed(arg) = arg else {
    421                 unreachable!()
    422             };
    423             let (ty, borrowed) = match arg.ty.as_ref() {
    424                 syn::Type::Reference(reference) if reference.mutability.is_some() => {
    425                     (reference.elem.as_ref(), true)
    426                 }
    427                 ty => (ty, false),
    428             };
    429             let ident = match ty {
    430                 syn::Type::Path(path) => path.path.segments.last().map(|s| &s.ident),
    431                 _ => None,
    432             };
    433             let (slot, value) = match ident {
    434                 Some(ident) if ident == "PgPool" && !borrowed => {
    435                     (&mut has_pool, quote! { __taler_pool })
    436                 }
    437                 Some(ident) if ident == "PoolConnection" && !borrowed => {
    438                     (&mut has_conn, quote! { __taler_conn })
    439                 }
    440                 Some(ident) if ident == "PgConnection" => (
    441                     &mut has_conn,
    442                     if borrowed {
    443                         quote! { &mut *__taler_conn }
    444                     } else {
    445                         quote! { __taler_conn.detach() }
    446                     },
    447                 ),
    448                 _ => {
    449                     return Err(Error::new_spanned(
    450                         &arg.ty,
    451                         "expected PgPool, PoolConnection<Postgres>, PgConnection, or &mut PgConnection",
    452                     ));
    453                 }
    454             };
    455             if std::mem::replace(slot, true) {
    456                 return Err(Error::new_spanned(
    457                     &arg.ty,
    458                     "expected at most one pool and one connection",
    459                 ));
    460             }
    461             args.push(value);
    462         }
    463         let acquire = has_conn.then(|| quote! {
    464             let mut __taler_conn = __taler_pool.acquire().await
    465                 .unwrap_or_else(|e| panic!("{}: acquire test connection: {e}", __taler_test_name));
    466         });
    467         Ok(quote! {
    468             async |__taler_pool: ::sqlx::PgPool| {
    469                 #acquire
    470                 #name(#(#args),*).await
    471             }
    472         })
    473     };
    474     let runner = (|input: syn::parse::ParseStream<'_>| {
    475         if input.peek(syn::Ident) && input.peek2(syn::Token![=]) {
    476             let mut sql_dir = None;
    477             let mut component = None;
    478             while !input.is_empty() {
    479                 let key: syn::Ident = input.parse()?;
    480                 input.parse::<syn::Token![=]>()?;
    481                 let value: Expr = input.parse()?;
    482                 let slot = match key.to_string().as_str() {
    483                     "sql_dir" => &mut sql_dir,
    484                     "component" => &mut component,
    485                     _ => return Err(Error::new(key.span(), "expected sql_dir or component")),
    486                 };
    487                 if slot.replace(value).is_some() {
    488                     return Err(Error::new(key.span(), "duplicate db_test option"));
    489                 }
    490                 if !input.is_empty() {
    491                     input.parse::<syn::Token![,]>()?;
    492                 }
    493             }
    494             let sql_dir = sql_dir.ok_or_else(|| input.error("missing sql_dir"))?;
    495             let component = component.ok_or_else(|| input.error("missing component"))?;
    496             let callback = callback()?;
    497             return Ok(quote! {
    498                 ::taler_test_utils::db::run_db_test_manual(
    499                     ::std::path::Path::new(#sql_dir), #component, __taler_test_name, #callback
    500                 )
    501             });
    502         }
    503         let source: Expr = if input.is_empty() {
    504             syn::parse_quote!(crate::constants::CONFIG_SOURCE)
    505         } else {
    506             input.parse()?
    507         };
    508         if matches!(&source, Expr::Path(path) if path.path.is_ident("raw")) {
    509             if sig.inputs.len() != 1 {
    510                 return Err(Error::new_spanned(
    511                     sig,
    512                     "raw db_test requires one PgConnectOptions argument",
    513                 ));
    514             }
    515             Ok(quote! {
    516                 ::taler_test_utils::db::run_db_test_raw(__taler_test_name, #name)
    517             })
    518         } else {
    519             let callback = callback()?;
    520             Ok(quote! {
    521                 ::taler_test_utils::db::run_db_test(#source, __taler_test_name, #callback)
    522             })
    523         }
    524     })
    525     .parse2(attr)?;
    526     let output = &sig.output;
    527     let attrs = &input.attrs;
    528     let vis = &input.vis;
    529     let body = &input.block;
    530     Ok(quote! {
    531         #(#attrs)*
    532         #[test]
    533         #vis fn #name() #output {
    534             #sig #body
    535             let __taler_test_name = concat!(module_path!(), "::", stringify!(#name));
    536             #runner
    537         }
    538     })
    539 }