Skip to main content

protovalidate_buffa_macros/
lib.rs

1//! `#[connect_impl]` — inserts `req.validate()?` at the top of every Connect
2//! service handler method in an `impl` block whose request parameter is an
3//! `OwnedView<_>`. Single-site safety net: add it once to the service impl
4//! and every present-and-future handler is validated on entry.
5//!
6//! Non-handler `async fn`s inside the same `impl` block are left alone
7//! (they lack an `OwnedView<_>` parameter, so the macro skips them).
8
9use proc_macro::TokenStream;
10use proc_macro2::TokenStream as TokenStream2;
11use quote::quote;
12use syn::{Error, FnArg, ImplItem, ItemImpl, PatType, Type, TypePath, parse_macro_input};
13
14#[proc_macro_attribute]
15pub fn connect_impl(attr: TokenStream, input: TokenStream) -> TokenStream {
16    if !attr.is_empty() {
17        return Error::new_spanned(
18            TokenStream2::from(attr),
19            "protovalidate_buffa::connect_impl takes no arguments",
20        )
21        .to_compile_error()
22        .into();
23    }
24
25    let mut item = parse_macro_input!(input as ItemImpl);
26
27    for impl_item in &mut item.items {
28        if let ImplItem::Fn(f) = impl_item
29            && let Some(arg_ident) = find_owned_view_arg(&f.sig)
30        {
31            let pv_ident =
32                proc_macro2::Ident::new("__protovalidate_buffa_req_owned", arg_ident.span());
33
34            let decode: syn::Stmt = syn::parse_quote! {
35                let #pv_ident = #arg_ident.to_owned_message();
36            };
37            let validate: syn::Stmt = syn::parse_quote! {
38                <_ as ::protovalidate_buffa::Validate>::validate(&#pv_ident)
39                    .map_err(::protovalidate_buffa::ValidationError::into_connect_error)?;
40            };
41
42            f.block.stmts.insert(0, decode);
43            f.block.stmts.insert(1, validate);
44        }
45    }
46
47    TokenStream::from(quote! { #item })
48}
49
50/// Returns the ident of the first parameter whose type is a path ending in
51/// `OwnedView` (e.g. `OwnedView<pb::CreateFooRequestView<'static>>`).
52/// Non-handler methods that lack such a parameter return `None`.
53fn find_owned_view_arg(sig: &syn::Signature) -> Option<syn::Ident> {
54    for arg in &sig.inputs {
55        if let FnArg::Typed(PatType { pat, ty, .. }) = arg
56            && is_owned_view(ty)
57            && let syn::Pat::Ident(pat_ident) = pat.as_ref()
58        {
59            return Some(pat_ident.ident.clone());
60        }
61    }
62    None
63}
64
65fn is_owned_view(ty: &Type) -> bool {
66    if let Type::Path(TypePath { path, .. }) = ty
67        && let Some(last) = path.segments.last()
68    {
69        return last.ident == "OwnedView";
70    }
71    false
72}