|
| 1 | +use proc_macro2::TokenStream; |
| 2 | +use quote::{ToTokens, quote}; |
| 3 | +use syn::{LitBool, Path, Result, Type, meta::ParseNestedMeta}; |
| 4 | + |
| 5 | +use crate::validation::Validation; |
| 6 | + |
| 7 | +pub struct Custom { |
| 8 | + is_async: bool, |
| 9 | + error_type: Type, |
| 10 | + function_path: Path, |
| 11 | +} |
| 12 | + |
| 13 | +impl Validation for Custom { |
| 14 | + fn parse(meta: &ParseNestedMeta<'_>) -> Result<Self> { |
| 15 | + let mut is_async = false; |
| 16 | + let mut error_type: Option<Type> = None; |
| 17 | + let mut function_path: Option<Path> = None; |
| 18 | + |
| 19 | + meta.parse_nested_meta(|meta| { |
| 20 | + if meta.path.is_ident("async") { |
| 21 | + if let Ok(value) = meta.value() { |
| 22 | + let lit: LitBool = value.parse()?; |
| 23 | + is_async = lit.value; |
| 24 | + } else { |
| 25 | + is_async = true; |
| 26 | + } |
| 27 | + |
| 28 | + Ok(()) |
| 29 | + } else if meta.path.is_ident("error") { |
| 30 | + error_type = Some(meta.value()?.parse()?); |
| 31 | + |
| 32 | + Ok(()) |
| 33 | + } else if meta.path.is_ident("function") { |
| 34 | + function_path = Some(meta.value()?.parse()?); |
| 35 | + |
| 36 | + Ok(()) |
| 37 | + } else { |
| 38 | + Err(meta.error("unknown parameter")) |
| 39 | + } |
| 40 | + })?; |
| 41 | + |
| 42 | + let Some(error_type) = error_type else { |
| 43 | + return Err(meta.error("missing error parameter")); |
| 44 | + }; |
| 45 | + let Some(function_path) = function_path else { |
| 46 | + return Err(meta.error("missing function parameter")); |
| 47 | + }; |
| 48 | + |
| 49 | + Ok(Custom { |
| 50 | + is_async, |
| 51 | + error_type, |
| 52 | + function_path, |
| 53 | + }) |
| 54 | + } |
| 55 | + |
| 56 | + fn is_async(&self) -> bool { |
| 57 | + self.is_async |
| 58 | + } |
| 59 | + |
| 60 | + fn error_type(&self) -> TokenStream { |
| 61 | + self.error_type.to_token_stream() |
| 62 | + } |
| 63 | + |
| 64 | + fn tokens(&self, expr: &TokenStream) -> TokenStream { |
| 65 | + let function_path = &self.function_path; |
| 66 | + |
| 67 | + if self.is_async { |
| 68 | + quote! { |
| 69 | + #function_path(&#expr).await |
| 70 | + } |
| 71 | + } else { |
| 72 | + quote! { |
| 73 | + #function_path(&#expr) |
| 74 | + } |
| 75 | + } |
| 76 | + } |
| 77 | +} |
0 commit comments