Skip to main content

buffa_codegen/
serde_input.rs

1//! Caller input policies for the cleanup visitor, separate from field layout.
2use proc_macro2::TokenStream;
3use quote::quote;
4use syn::{parse::Parser as _, Meta, Path};
5
6/// Why a caller attribute cannot be preserved by the cleanup JSON visitor.
7#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
8#[non_exhaustive]
9pub enum ErrorReason {
10    /// The visitor cannot implement the requested input customization.
11    #[error("unsupported caller JSON input attribute on a cleanup-enabled message")]
12    Unsupported,
13    /// A Serde default is neither bare nor a string containing a function path.
14    #[error("invalid caller JSON default on a cleanup-enabled message")]
15    InvalidDefault,
16    /// Attribute syntax could not be parsed without guessing its policy.
17    #[error("invalid caller JSON attribute syntax on a cleanup-enabled message")]
18    InvalidSyntax,
19}
20
21#[derive(Default)]
22pub(crate) struct Policy {
23    skips: Vec<Vec<Meta>>,
24    pub(crate) defaults: Vec<DefaultRule>,
25}
26pub(crate) struct DefaultRule {
27    conditions: Vec<Meta>,
28    path: Option<Path>,
29}
30impl DefaultRule {
31    pub(crate) fn expression(&self) -> TokenStream {
32        match &self.path {
33            Some(path) => quote! { #path() },
34            None => quote! { ::core::default::Default::default() },
35        }
36    }
37    pub(crate) fn gate(&self, tokens: TokenStream) -> TokenStream {
38        gate(condition(&self.conditions), tokens)
39    }
40}
41fn condition(conditions: &[Meta]) -> Option<TokenStream> {
42    (!conditions.is_empty()).then(|| quote! { all(#(#conditions),*) })
43}
44pub(crate) fn gate(condition: Option<TokenStream>, tokens: TokenStream) -> TokenStream {
45    match condition {
46        Some(condition) => quote! { #[cfg(#condition)] #tokens },
47        None => tokens,
48    }
49}
50impl Policy {
51    pub(crate) fn acceptance(&self) -> Option<TokenStream> {
52        if self.skips.is_empty() {
53            return None;
54        }
55        let skips = self.skips.iter().map(|parts| {
56            let condition = condition(parts);
57            condition.unwrap_or_else(|| quote! { all() })
58        });
59        Some(quote! { not(any(#(#skips),*)) })
60    }
61}
62fn options(
63    list: &syn::MetaList,
64) -> Result<syn::punctuated::Punctuated<Meta, syn::Token![,]>, ErrorReason> {
65    list.parse_args_with(syn::punctuated::Punctuated::<Meta, syn::Token![,]>::parse_terminated)
66        .map_err(|_| ErrorReason::InvalidSyntax)
67}
68fn collect(
69    meta: &Meta,
70    conditions: &[Meta],
71    policy: &mut Policy,
72    container: bool,
73) -> Result<(), ErrorReason> {
74    let Meta::List(list) = meta else {
75        return Ok(());
76    };
77    if list.path.is_ident("cfg_attr") {
78        let mut nested = options(list)?.into_iter();
79        let predicate = nested.next().ok_or(ErrorReason::InvalidSyntax)?;
80        let mut conditions = conditions.to_vec();
81        conditions.push(predicate);
82        for meta in nested {
83            collect(&meta, &conditions, policy, container)?;
84        }
85    } else if list.path.is_ident("cfg") {
86        // Removing a field also affects binary/text/reflection implementations.
87        // It cannot be treated as a JSON-only input policy.
88        return Err(ErrorReason::Unsupported);
89    } else if list.path.is_ident("serde") {
90        for option in options(list)? {
91            if option.path().is_ident("skip_serializing")
92                || option.path().is_ident("skip_serializing_if")
93                || option.path().is_ident("serialize_with")
94            {
95                continue;
96            }
97            if container {
98                return Err(ErrorReason::Unsupported);
99            }
100            if option.path().is_ident("skip") || option.path().is_ident("skip_deserializing") {
101                if !matches!(option, Meta::Path(_)) {
102                    return Err(ErrorReason::InvalidSyntax);
103                }
104                policy.skips.push(conditions.to_vec());
105            } else if option.path().is_ident("default") {
106                let path = match option {
107                    Meta::Path(_) => None,
108                    Meta::NameValue(value) => {
109                        let syn::Expr::Lit(syn::ExprLit {
110                            lit: syn::Lit::Str(path),
111                            ..
112                        }) = value.value
113                        else {
114                            return Err(ErrorReason::InvalidDefault);
115                        };
116                        Some(
117                            path.parse::<Path>()
118                                .map_err(|_| ErrorReason::InvalidDefault)?,
119                        )
120                    }
121                    _ => return Err(ErrorReason::InvalidDefault),
122                };
123                policy.defaults.push(DefaultRule {
124                    conditions: conditions.to_vec(),
125                    path,
126                });
127            } else {
128                // Custom decoders, aliases and flattening must not appear to
129                // work merely because Serialize accepts their attributes.
130                return Err(ErrorReason::Unsupported);
131            }
132        }
133    }
134    Ok(())
135}
136pub(crate) fn parse(attributes: &TokenStream, container: bool) -> Result<Policy, ErrorReason> {
137    let mut policy = Policy::default();
138    for attribute in syn::Attribute::parse_outer
139        .parse2(attributes.clone())
140        .map_err(|_| ErrorReason::InvalidSyntax)?
141    {
142        collect(&attribute.meta, &[], &mut policy, container)?;
143    }
144    Ok(policy)
145}
146
147#[cfg(test)]
148mod tests {
149    use super::*;
150    #[test]
151    fn defaults_and_skips_retain_nested_conditions() {
152        let policy = parse(
153            &quote! {
154                #[serde(default)]
155                #[cfg_attr(feature = "selected", cfg_attr(all(), serde(skip_deserializing)))]
156            },
157            false,
158        )
159        .unwrap();
160        assert_eq!(policy.defaults.len(), 1);
161        assert_eq!(
162            policy.defaults[0].expression().to_string(),
163            quote! { ::core::default::Default::default() }.to_string()
164        );
165        assert_eq!(policy.skips[0].len(), 2);
166    }
167    #[test]
168    fn malformed_defaults_have_typed_redacted_errors() {
169        for attribute in [
170            quote! { #[serde(default = 17)] },
171            quote! { #[serde(default = "private path!")] },
172        ] {
173            assert!(matches!(
174                parse(&attribute, false),
175                Err(ErrorReason::InvalidDefault)
176            ));
177        }
178        assert!(matches!(
179            parse(&quote! { #[cfg(any())] }, false),
180            Err(ErrorReason::Unsupported)
181        ));
182    }
183}