Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support #[serde(validate = "function")] for container, compatible with validator crate #2891

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 33 additions & 2 deletions serde_derive/src/de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ pub fn expand_derive_deserialize(input: &mut syn::DeriveInput) -> syn::Result<To
let params = Parameters::new(&cont);
let (de_impl_generics, _, ty_generics, where_clause) = split_with_de_lifetime(&params);
let body = Stmts(deserialize_body(&cont, &params));
let validated_body = validate_body(&cont, body);
let delife = params.borrowed.de_lifetime();
let serde = cont.attrs.serde_path();

Expand All @@ -40,7 +41,7 @@ pub fn expand_derive_deserialize(input: &mut syn::DeriveInput) -> syn::Result<To
__D: #serde::Deserializer<#delife>,
{
#used
#body
#validated_body
}
}
}
Expand All @@ -54,7 +55,7 @@ pub fn expand_derive_deserialize(input: &mut syn::DeriveInput) -> syn::Result<To
where
__D: #serde::Deserializer<#delife>,
{
#body
#validated_body
}

#fn_deserialize_in_place
Expand Down Expand Up @@ -273,6 +274,36 @@ fn borrowed_lifetimes(cont: &Container) -> BorrowedLifetimes {
}
}

fn validate_body(cont: &Container, body: Stmts) -> TokenStream {
let serde = cont.attrs.serde_path();
let mut validations: Vec<TokenStream> = cont
.attrs
.validate()
.iter()
.map(|validate| {
quote! {
#validate(&body).map_err(#serde::de::Error::custom)?;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Probably it is better to use From trait here and below?

Copy link
Author

@zao111222333 zao111222333 Feb 13, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You mean the signature of validation should be fn <E: serde::de::Error>(&T) -> Result<(), impl Into<E>>?

In this case, if we want to call #[serde(validate = "validator::Validate::validate")] to use validator, the only way is to add follow code within serde, since Rust only allow local impl for trait E

impl<E: serde::de::Error> From<validator::ValidationErrors> for E { }

It will introduce a new dependence for serde, I don't know if we can do that

Well, there are only serde::de::Error::cutom and serde::de::Error::invalid_value that are suitable for validation, I think just use serde::de::Error::cutom is a good approach :)

}
})
.collect();
if cont.attrs.validator() {
validations.push(
quote! {
validator::Validate::validate(&body).map_err(#serde::de::Error::custom)?;
},
);
}
if validations.is_empty() {
quote! { #body }
} else {
quote! {
let body = { #body }?;
#(#validations)*
Ok(body)
}
}
}

fn deserialize_body(cont: &Container, params: &Parameters) -> Fragment {
if cont.attrs.transparent() {
deserialize_transparent(cont, params)
Expand Down
22 changes: 22 additions & 0 deletions serde_derive/src/internals/attr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,8 @@ pub struct Container {
remote: Option<syn::Path>,
identifier: Identifier,
serde_path: Option<syn::Path>,
validate: Vec<syn::ExprPath>,
validator: bool,
is_packed: bool,
/// Error message generated when type can't be deserialized
expecting: Option<String>,
Expand Down Expand Up @@ -256,6 +258,8 @@ impl Container {
let mut remote = Attr::none(cx, REMOTE);
let mut field_identifier = BoolAttr::none(cx, FIELD_IDENTIFIER);
let mut variant_identifier = BoolAttr::none(cx, VARIANT_IDENTIFIER);
let mut validate = VecAttr::none(cx, VALIDATE);
let mut validator = BoolAttr::none(cx, VALIDATOR);
let mut serde_path = Attr::none(cx, CRATE);
let mut expecting = Attr::none(cx, EXPECTING);
let mut non_exhaustive = false;
Expand Down Expand Up @@ -486,6 +490,14 @@ impl Container {
if let Some(path) = parse_lit_into_path(cx, CRATE, &meta)? {
serde_path.set(&meta.path, path);
}
} else if meta.path == VALIDATE {
// #[serde(validate = "...")]
if let Some(path) = parse_lit_into_expr_path(cx, VALIDATE, &meta)? {
validate.insert(&meta.path, path);
}
} else if meta.path == VALIDATOR {
// #[serde(validator)]
validator.set_true(meta.path);
} else if meta.path == EXPECTING {
// #[serde(expecting = "a message")]
if let Some(s) = get_lit_str(cx, EXPECTING, &meta)? {
Expand Down Expand Up @@ -539,6 +551,8 @@ impl Container {
remote: remote.get(),
identifier: decide_identifier(cx, item, field_identifier, variant_identifier),
serde_path: serde_path.get(),
validate: validate.get(),
validator: validator.get(),
is_packed,
expecting: expecting.get(),
non_exhaustive,
Expand Down Expand Up @@ -597,6 +611,14 @@ impl Container {
self.remote.as_ref()
}

pub fn validate(&self) -> &[syn::ExprPath] {
self.validate.as_ref()
}

pub fn validator(&self) -> bool {
self.validator
}

pub fn is_packed(&self) -> bool {
self.is_packed
}
Expand Down
2 changes: 2 additions & 0 deletions serde_derive/src/internals/symbol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ pub const TRANSPARENT: Symbol = Symbol("transparent");
pub const TRY_FROM: Symbol = Symbol("try_from");
pub const UNTAGGED: Symbol = Symbol("untagged");
pub const VARIANT_IDENTIFIER: Symbol = Symbol("variant_identifier");
pub const VALIDATE: Symbol = Symbol("validate");
pub const VALIDATOR: Symbol = Symbol("validator");
pub const WITH: Symbol = Symbol("with");

impl PartialEq<Symbol> for Ident {
Expand Down
1 change: 1 addition & 0 deletions test_suite/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,4 @@ serde = { path = "../serde", features = ["rc"] }
serde_derive = { path = "../serde_derive", features = ["deserialize_in_place"] }
serde_test = "1.0.176"
trybuild = { version = "1.0.97", features = ["diff"] }
validator = { version = "0.20", features = ["derive"] }
Loading