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::{parse_macro_input, Error, FnArg, ImplItem, ItemImpl, PatType, Type, TypePath};
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            if let Some(arg_ident) = find_owned_view_arg(&f.sig) {
30                let pv_ident =
31                    proc_macro2::Ident::new("__protovalidate_buffa_req_owned", arg_ident.span());
32
33                let decode: syn::Stmt = syn::parse_quote! {
34                    let #pv_ident = #arg_ident.to_owned_message();
35                };
36                let validate: syn::Stmt = syn::parse_quote! {
37                    <_ as ::protovalidate_buffa::Validate>::validate(&#pv_ident)
38                        .map_err(::protovalidate_buffa::ValidationError::into_connect_error)?;
39                };
40
41                f.block.stmts.insert(0, decode);
42                f.block.stmts.insert(1, validate);
43            }
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            if is_owned_view(ty) {
57                if let syn::Pat::Ident(pat_ident) = pat.as_ref() {
58                    return Some(pat_ident.ident.clone());
59                }
60            }
61        }
62    }
63    None
64}
65
66fn is_owned_view(ty: &Type) -> bool {
67    if let Type::Path(TypePath { path, .. }) = ty {
68        if let Some(last) = path.segments.last() {
69            return last.ident == "OwnedView";
70        }
71    }
72    false
73}