use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use syn::spanned::Spanned;
use crate::types::ValidateField;
use crate::utils::{
CrateName, FieldOptionality, field_optionality, is_field_sensitive, quote_code, quote_message,
};
#[derive(Debug, Clone, darling::FromMeta)]
pub struct MustMatch {
pub code: Option<String>,
pub message: Option<String>,
pub other: syn::Path,
}
pub fn check_must_match_validator_form(
field: &ValidateField,
field_name: &str,
struct_ident: &syn::Ident,
all_fields: &[&syn::Field],
) {
if let Some(must_match) = &field.must_match {
let other_field = must_match
.other
.get_ident()
.expect("Cannot get ident from `other` field value")
.to_string();
if !all_fields
.iter()
.any(|f| f.ident.as_ref().is_some_and(|i| i == &other_field))
{
proc_macro_error2::abort!(
must_match.other.span(), "Invalid attribute for #[validate(must_match(...))] on field `{}`:", field_name;
note = "The `other` field doesn't exist in the struct `{}`", struct_ident;
help = "Add the field `{}` to the struct", other_field
)
}
}
}
fn value_as_option_ref(expr: TokenStream2, optionality: FieldOptionality) -> TokenStream2 {
match optionality {
FieldOptionality::NotOptional => quote!(::std::option::Option::Some(&#expr)),
FieldOptionality::Option => quote!(#expr.as_ref()),
FieldOptionality::OptionOption => quote!(#expr.as_ref().and_then(|inner| inner.as_ref())),
FieldOptionality::Delta => quote!(#expr.value()),
}
}
pub fn tokens(
crate_name: &CrateName,
must_match: MustMatch,
field_name: &syn::Ident,
field_name_str: &str,
all_fields: &[&syn::Field],
) -> TokenStream2 {
let o = must_match.other;
let other_name = o
.get_ident()
.expect("Cannot get ident from `other` field value")
.to_string();
let main_expr = value_as_option_ref(
quote!(self.#field_name),
field_optionality(field_name_str, all_fields),
);
let other_expr =
value_as_option_ref(quote!(self.#o), field_optionality(&other_name, all_fields));
let message = quote_message(must_match.message);
let code = quote_code(crate_name, must_match.code, "must_match");
let other_param = if is_field_sensitive(&other_name, all_fields) {
quote!()
} else {
quote!(err.add_param(::std::borrow::Cow::from("other"), &must_match_other);)
};
let value_param = if is_field_sensitive(field_name_str, all_fields) {
quote!()
} else {
quote!(err.add_param(::std::borrow::Cow::from("value"), &must_match_value);)
};
quote! {
if let ::std::option::Option::Some(must_match_value) = #main_expr {
let must_match_other = #other_expr;
if !#crate_name::validate_must_match(
::std::option::Option::Some(must_match_value),
must_match_other,
) {
#code
#message
#other_param
#value_param
errors.add(#field_name_str, err);
}
}
}
}